﻿using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using Jst.Application.Contracts.Services;
using Jst.Core.Utility;
using Microsoft.AspNetCore.Http;

namespace Jst.Infrastructure.Web.Authentication
{
    /// <summary>
    /// 上下文信息配置
    /// </summary>
    public class AspNetUser : IHttpContextUser
    {
        private readonly IHttpContextAccessor _accessor;

        public AspNetUser(IHttpContextAccessor accessor)
        {
            _accessor = accessor;
        }
        public string Account => _accessor.HttpContext.User.Identity.Name;

        public long ID => GetClaimValueByType("Jti").FirstOrDefault().ObjectToLong();


        public bool IsAuthenticated()
        {
            return _accessor.HttpContext.User.Identity.IsAuthenticated;
        }

        public string GetToken()
        {
            return _accessor.HttpContext.Request.Headers["Authorization"].ObjectToString().Replace("Bearer ", "");
        }

        #region 类型转换
        public List<string> GetUserInfoFromToken(string ClaimType)
        {

            var jwtHandler = new JwtSecurityTokenHandler();
            if (!string.IsNullOrEmpty(GetToken()))
            {
                JwtSecurityToken jwtToken = jwtHandler.ReadJwtToken(GetToken());

                return (from item in jwtToken.Claims
                        where item.Type == ClaimType
                        select item.Value).ToList();
            }
            else
            {
                return new List<string>() { };
            }
        }

        public IEnumerable<Claim> GetClaimsIdentity()
        {
            return _accessor.HttpContext.User.Claims;
        }

        public List<string> GetClaimValueByType(string ClaimType)
        {

            var ClaimValue = (from item in GetClaimsIdentity()
                              where item.Type == ClaimType
                              select item.Value).ToList();

            return ClaimValue;

        }
        #endregion

    }
}
